package com.novel.crawl.common.dao.impl;

import com.novel.common.dao.impl.BaseDaoImpl;
import com.novel.common.entity.Entity;
import com.novel.crawl.common.dao.BookDao;
import com.novel.crawl.common.entity.Book;
import org.bson.types.ObjectId;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author 奔波儿灞
 * @since 1.0
 */
@Repository
public class BookDaoImpl extends BaseDaoImpl<Book> implements BookDao {

    @Override
    public List<Book> findBatchByBookIdStartAndSource(String bookId, String source, int size) {
        // 需要手动转换成ObjectId
        ObjectId id = new ObjectId(bookId);
        Criteria criteria = Criteria.where(Entity.ID_KEY).gt(id).and(Book.SOURCE_KEY).is(source);
        Query query = query(criteria).limit(size);
        return find(query);
    }

    @Override
    public Book findByUrl(String url) {
        Query query = query(Criteria.where(Book.URL_KEY).is(url));
        return findOne(query);
    }

    @Override
    public Page<Book> search(String word, Pageable pageable) {
        Criteria criteria = Criteria.where(Book.NAME_KEY).regex("^" + word);
        return page(criteria, pageable);
    }

    @Override
    public void incrementView(String bookId) {
        Query query = query(Criteria.where(Entity.ID_KEY).is(bookId));
        Update update = new Update().inc(Book.VIEW_KEY, 1);
        update(query, update);
    }

}
